import { getShopDetail } from '../api/coup'
import { checkPromotionProductList } from '../api/coupContent'
import { getActivitySkuListData, cretedActivityApi, getActivityListData } from '../api/activityApi'
import moment from 'moment'
import { requerconetnt, requerconetntAll } from '../utils/requestContent'

class InitRunAutoActivity {
    constructor() {
        this.dly_activity_list = [] // 总的任务列表
        this.cb_list = [] // 递归任务列表
        this.run_item = null // 当前进行的任务
        this.checkyesgoods = [] // 塞选过可以参加活动的商品
        this.checkActivityTime = null // 塞选的参数
        this.skuLists = [] // 获取到goods 对应的最新sku数据

        this.shopInfo = null // 店铺信息
        this.storegeText = 'dly_activity_list_'
        this.autoLogsText = 'dly_auto_activity_logs_'
        this.run_status = false // 是否在执行
        this.outerket = null

        this.loginOuterStatus = false

        this.getActivityListDataInit = {
            campaign_status: 2,
            shop_stype: '',
            page: 1,
            pageSize: 100
        }
        this.getActivityList()

    }
    /**
     * 获取进行中的任务，查找到正在处理的任务
     */
    async getActivitistipRun() {
        // if (this.run_status) {
        //     console.log('正在执行任务，请稍后')
        //     return
        // }
        // this.run_status = true
        const getOnlist = await getActivityListData(this.getActivityListDataInit)
        console.log('252务0000....', getOnlist)
        // const getPlyrtAlls = []
        if (!getOnlist.code) {
            let { total, data } = getOnlist

            if (!data || !data.flash_list) {
                this.getActivityListDataInit.page = 1
                // this.run_status = false
                return true
            }
            data.flash_list.forEach(item => {
                if (item.campaign_status == 6) {
                    // this.run_item = item
                    throw new Error('存在处理中的任务 无法确定数据的准确性 稍后再试')
                }
            })
            if (total > this.getActivityListDataInit.pageSize * this.getActivityListDataInit.page) {
                this.getActivityListDataInit.page++
                return this.getActivitistipRun()
            }
            this.getActivityListDataInit.page = 1
            // this.run_status = false
            return true
        }
        throw new Error(getOnlist)

    }

    /**
     * @name 获取任务并检查活动是否可以设置
     */
    async getActivityList() {
        const _this = this
        console.log('获取任务并检查活动是否可以设置')
        if (_this.loginOuterStatus) {
            return
        }

        if (_this.run_status) {
            console.log('正在执行任务，请稍后')
            return
        }

        _this.run_status = true
        if (_this.outerket) {
            clearTimeout(_this.outerket)
            _this.outerket = null
        }
        _this.outerket = setTimeout(function () {
            _this.run_status = false
        }, 5000)
        if (!_this.shopInfo || !_this.shopInfo.id) {
            _this.loginOuterStatus = true
            return
        }
        _this.storegeText = `dly_activity_list_${_this.shopInfo.id}`
        // console.log('获取店铺信息', _this.shopInfo)
        _this.autoLogsText = `dly_auto_activity_logs_${_this.shopInfo.id}`
        // chrome.storage.local.get(_this.autoLogsText, function (result) {
        //     if (result[_this.autoLogsText]) {
        //         console.log('获取日志', result[_this.autoLogsText])
        //     }

        // })
        console.log('_this.storegeText', _this.storegeText)
        // 获取任务列表
        chrome.storage.local.get([_this.storegeText], async function (result) {
            console.log('result', result)
            if (result[_this.storegeText]) {
                _this.dly_activity_list = result[_this.storegeText]
                _this.cb_list = result[_this.storegeText]
                // console.log('获取任务列表', _this.dly_activity_list)

                const cheackLogin = await getShopDetail()
                // console.log('获取店铺信息', cheackLogin)
                if (!cheackLogin) {
                    _this.run_status = false
                    _this.loginOuterStatus = true
                    // 窗口通知
                    notify({
                        title: '抖羚羊通知',
                        message: "后台正在设置限时限量购活动，抖店登陆已过期，请前往登陆抖店",
                        // buttons: [{
                        //     title: '打开抖店',
                        //     cb: function () {
                        //         chrome.tabs.create({ url: 'https://fxg.jinritemai.com/ffa/marketing/coupon/home' }, (id) => {
                        //         })
                        //     }
                        // }],
                        requireInteraction: false,
                        timeout: 2000
                    })
                    return
                }
                _this.shopInfo = cheackLogin.data

                _this.runSetActivityFunc()
                // console.log('获取任务列表', result[_this.storegeText])
            } else {
                console.log('没有可以设置的任务活动')
                _this.run_status = false
            }
        })
    }
    /**
     * @name 递归调用设置活动开始入口
     */
    async runSetActivityFunc() {
        const getConter = await this.getActivitistipRun().catch(err => {
            // console.log('getConter', err)
            return false
        })
        console.log('getConter1111', getConter)
        if (!getConter) {
            this.run_status = false
            console.log('存在处理中的任务 无法确定数据的准确性 稍后再试')
            return
        }

        this.cb_list = this.cb_list.filter((item, index) => {
            const { addLtaLpConfig } = item
            let { promotion_goods } = addLtaLpConfig
            const noter_goods = promotion_goods.filter((goods) => {
                // console.log('goods', goods)
                return goods.autoNumber > goods.useNumber
                // return goods.product_id !== '3690525630887231682'
            })
            item.addLtaLpConfig.promotion_goods = noter_goods
            // console.log('promotion_goods', promotion_goods)
            return noter_goods.length > 0

        })

        // 判断剩余次数
        const notSetItem = this.cb_list.splice(0, 1)
        // console.log('notSetItem', notSetItem)
        if (notSetItem.length > 0) {
            this.run_item = notSetItem[0]
            // 设置通知到前台 当前任务正在处理
            // this.dly_activity_list.forEach((item, index) => {
            //     if (item.id == this.run_item.id) {
            //         item.status = 1
            //     } else {
            //         item.status = item.status == 3 ? 3 : 0
            //     }
            // })
            const _this = this
            chrome.storage.local.get([_this.storegeText], async function (result) {
                // console.log('result111', result[_this.storegeTex])
                if (!result[_this.storegeText]) {
                    return
                }
                const upConters = result[_this.storegeText]
                upConters.forEach((item, index) => {
                    if (item.id == _this.run_item.id) {
                        item.status = 1
                    } else {
                        item.status = item.status == 3 ? 3 : 0
                    }
                })
                _this.dly_activity_list = upConters
                chrome.storage.local.set({ [_this.storegeText]: _this.dly_activity_list }, function () {
                    requerconetntAll('', 'dly_reload_autodata').then(res => {
                        console.log('通知页面刷新数据成功6655')
                    })
                })

            })


            this.setActivity()
        } else {
            this.run_item = null
            // console.log('没有可以设置的任务活动递归结束 这里为结束这次任务 放出内存')
            this.run_status = false
            // this.dly_activity_list.forEach((item, index) => {
            //     item.status = item.status == 3 ? 3 : 0
            // })
            const _this = this
            chrome.storage.local.get([_this.storegeText], async function (result) {
                if (!result[_this.storegeText]) {
                    return
                }
                const upConters = result[_this.storegeText]
                upConters.forEach((item, index) => {
                    item.status = item.status == 3 ? 3 : 0
                })
                _this.dly_activity_list = upConters
                chrome.storage.local.set({ [_this.storegeText]: _this.dly_activity_list }, function () {
                    requerconetntAll('', 'dly_reload_autodata').then(res => {
                        console.log('通知页面刷新数据成功。。')
                    })
                })

            })

        }
    }
    /**
     * @name 检查活动所设置的时间的商品是否有冲突
     * @param {任务项} item 
     * @param {递归列表} list 
     * @returns 
     */
    async setActivity() {
        if (!this.run_item) {
            console.log('没有可以设置的任务活动最后一个 这里为结束这次任务 放出内存')
            this.run_status = false
            return
        }
        // 检查抖店登陆状态

        // 直接检查商品
        const { addLtaLpConfig, autoSetConfig } = this.run_item
        const { promotion_goods, activity_type, begin_time, end_time } = addLtaLpConfig
        const { actTimeType, timeTypRedou, hoursLen, minutesLen } = autoSetConfig
        const startDate = (new Date().getTime() / 1000).toFixed(0) * 1
        let endDate = ''
        const cheackObjectData = {
            "validate_type": 1,
            "participate_type": 1,
            "activity_tool_type": activity_type * 1,
            "start_time": startDate,
            "end_time": '',
            "product_infos": promotion_goods.map(trs => {
                return {
                    "product_id": trs.product_id,
                    "channel_type": 0,
                    "channel_id": "0"
                }
            })

        }


        if (actTimeType == 1) {
            const start = moment(begin_time);
            const end = moment(end_time);
            // 现在时间 加上 上面时间的差值
            endDate = startDate + end.diff(start) / 1000
        }
        if (actTimeType == 2 && timeTypRedou == 1) {
            // 现在时间加上多少小时
            endDate = startDate + hoursLen * 60 * 60
        }
        // 现在时间加上多少分钟
        if (actTimeType == 2 && timeTypRedou == 2) {
            endDate = startDate + minutesLen * 60
        }

        cheackObjectData.end_time = endDate
        this.checkActivityTime = cheackObjectData
        // console.log('要提交的数据', cheackObjectData)
        // 检查商品在所设置的时间段是否可用
        const cheackDataInfos = await checkPromotionProductList(cheackObjectData)
        // console.log('检查的结果', cheackDataInfos)

        if (!cheackDataInfos.code) {
            // 检查商品是否可用
            const { product_check_infos } = cheackDataInfos.data
            let notInActGoods = [] // 选中时间没有被占用的商品
            if (product_check_infos) {
                promotion_goods.forEach(prids => {
                    const getIdItem = product_check_infos[`${prids.product_id}_0_0`]
                    if (!getIdItem) {
                        notInActGoods.push(prids)
                    }
                })
            } else {
                notInActGoods = promotion_goods
            }
            if (notInActGoods && notInActGoods.length) {
                console.log('有没被设置的 可以进行设置', notInActGoods)
                // 设置成功后在对应的任务id 中的对应商品进行次数设置 非任务次数 而是商品次数
                this.checkyesgoods = notInActGoods
                this.cheackGoodsAndSkuPritr()
                return
            }
            console.log('不存在 递归继续')
            // 不存在 递归继续
            this.runSetActivityFunc()
        }


    }
    /**
     * @name 检查商品价格和库存
     * @param {任务配置} item 
     * @param {参加任务的商品列表} goods 
     * @param {检查活动商品留下的配置保证配置一致} ckeackConfig 
     * @returns 
     */
    async cheackGoodsAndSkuPritr() {
        const { addLtaLpConfig } = this.run_item
        const { start_time, end_time, activity_tool_type } = this.checkActivityTime
        // 获取sku  缺少库存的选择
        const getSkuPromet = {
            channel_products: this.checkyesgoods.map(trs => {
                return {
                    product_id: trs.product_id,
                }
            }),
            limit_stock_type: addLtaLpConfig.limit_stock_type,
            activity_tool_type,
            business_code: addLtaLpConfig.business_code,
            start_time,
            end_time
        }
        const skuapidata = await getActivitySkuListData(getSkuPromet)
        if (!skuapidata.code) {

            this.skuLists = skuapidata.data
            const formaters = this.formateData()
            if (formaters) {
                cretedActivityApi(formaters).then(res => {
                    console.log('创建活动的结果', res)
                    this.autoLogsSave(res, formaters)
                })
            } else {
                console.log('商品数据为空')
                this.runSetActivityFunc()
            }
            return
        }
        // sku错误 继续下一个任务 不再等待
        this.runSetActivityFunc()
    }
    formateData() {
        const { addLtaLpConfig, autoSetConfig } = this.run_item
        const { business_code, limit_stock_type, sold_out_type, stype, sub_stype, activity_type, time_set_type, order_expire_time, shop_stype, need_live, config_scope } = addLtaLpConfig
        const { stockSetType, stockPercentage, befoTitle } = autoSetConfig // 价格不匹配的处理方式
        const { start_time, end_time } = this.checkActivityTime

        const postUpDataInfo = {
            begin_time: moment(start_time * 1000).format('YYYY-MM-DD HH:mm:ss'),
            end_time: moment(end_time * 1000).format('YYYY-MM-DD HH:mm:ss'),
            pre_begin_time: moment(start_time * 1000).format('YYYY-MM-DD HH:mm:ss'), // 预热时间需要调整
            stype: stype + '',
            sub_stype: sub_stype + '',
            activity_type,
            title: '',
            time_set_type: time_set_type + '',
            order_expire_time, // 订单取消时间 秒
            shop_stype: shop_stype + '',
            sold_out_type: sold_out_type + '', // 0恢复原价后继续售卖 1停止售卖
            limit_stock_type: business_code === 'LimitQuantity' ? '0' : limit_stock_type + '',
            business_code, // LimitTime 限时 // LimitQuantity 限量 OrdinaryTimeBuy 普通
            promotion_goods: [],
            config_scope,
            from_page: "",
            need_live
        }

        this.skuLists.forEach(item => {
            const getFonterIter = this.checkyesgoods.find(trs => trs.product_id === item.product_id)
            if (getFonterIter) {
                const promotion_skus_outer = item.sku_list.map(trs => {
                    const skuOldItem = getFonterIter.promotion_skus.find(ttt => ttt.id == trs.sku_id)
                    if (skuOldItem) {

                        return {
                            id: skuOldItem.id + '',
                            user_limit: skuOldItem.user_limit,
                            camp_stock_num: (() => {
                                if (business_code == 'OrdinaryTimeBuy') {
                                    return 0
                                }
                                if (business_code === 'LimitTime') {
                                    if (limit_stock_type === 1) {
                                        return 0
                                    }
                                    return trs.origin_stock
                                }
                                switch (stockSetType) {
                                    case 1:
                                        return trs.origin_stock >= skuOldItem.stock ? skuOldItem.stock : trs.origin_stock
                                    case 2:
                                        // console.log('22', trs.origin_stock, skuOldItem.stock)
                                        return trs.origin_stock
                                    case 3:
                                        return Math.ceil(trs.origin_stock * stockPercentage / 100)
                                    default:
                                        break;
                                }
                            })(),
                            ...this.setSkuItemKeys(trs, skuOldItem)
                        }
                    }
                    return false
                })
                // 限时 限量必须全部 谱图需要删除无用的数据可以不用全部
                const upItemContent = {
                    // activity_limit_num: (() => {
                    //     let imer = promotion_skus_outer[0].camp_stock_num
                    //     if (business_code === 'LimitQuantity') {
                    //         imer = imer >= 1000 ? 1000 : imer
                    //     }
                    //     return imer
                    // })(),
                    channel_id: "0",
                    channel_type: 0,
                    cover: getFonterIter.cover,
                    product_id: getFonterIter.product_id,
                    promotion_skus: promotion_skus_outer,
                    title: getFonterIter.title
                }
                let pushkey = true
                // if (business_code === 'LimitTime') {
                //     console.log('promotion_skus_outer00', promotion_skus_outer)

                // }
                if (business_code === 'LimitQuantity' || business_code === 'LimitTime') {
                    // 限时限量不能库存为空
                    promotion_skus_outer.forEach(item => {
                        if (business_code == 'LimitQuantity') {
                            item.camp_stock_num = (item.camp_stock_num >= 1000 ? 1000 : item.camp_stock_num) + ''
                        }
                        if (item.camp_stock_num <= 0 && business_code !== 'OrdinaryTimeBuy') {
                            pushkey = false
                        }

                        if (item.price === 'del' || item.shop_svalue === 'del') {
                            pushkey = false
                        }
                        if (business_code == 'LimitTime' && limit_stock_type == 1) {
                            pushkey = true
                        }
                    })
                }
                if (business_code === 'OrdinaryTimeBuy') {
                    upItemContent.promotion_skus = promotion_skus_outer.filter(item => {
                        if (item.price === 'del' || item.shop_svalue === 'del') {
                            return false
                        }
                        return true
                    })
                    if (!upItemContent.promotion_skus.length) {
                        pushkey = false
                    }
                }

                pushkey && postUpDataInfo.promotion_goods.push(upItemContent)

            }
        })

        return postUpDataInfo.promotion_goods.length > 0 ? (() => {
            const titleForType = business_code == 'LimitQuantity' ? '限量' : business_code == 'LimitTime' ? '限时' : '普通'
            postUpDataInfo.title = `${befoTitle}${titleForType}A内${postUpDataInfo.promotion_goods.length} ${moment().format('YYYYMMDD HHmmss')}`.substring(0, 25)
            return postUpDataInfo
        })() : false
    }
    /**
     * 处理价格转换
     * @param {最新的数据} nowData 
     * @param {创建任务时的数据} oldData 
     * @returns key value
     */
    setSkuItemKeys(nowData, oldData) {
        let { price, shop_svalue } = oldData
        let { last_15_day_low_price, origin_price } = nowData
        const { addLtaLpConfig, autoSetConfig } = this.run_item
        const { shop_stype, business_code } = addLtaLpConfig
        const { notIsPre } = autoSetConfig // 价格不匹配的处理方式
        const maxPriceCherk = Number((Math.ceil(origin_price * (business_code == 'OrdinaryTimeBuy' ? 0.99 : 0.95))))
        const maxPrice = ~~(((origin_price - maxPriceCherk) >= 100 ? maxPriceCherk : origin_price - 100)) // 最低价格
        const priceWeiter = [100, (last_15_day_low_price && last_15_day_low_price <= maxPrice) ? last_15_day_low_price : maxPrice]
        switch (shop_stype) {
            case 1:
                return {
                    price: (() => {
                        if (price < priceWeiter[0] || price > priceWeiter[1]) {
                            if (notIsPre === 1) {
                                return priceWeiter[1]
                            }
                            return 'del'
                        }
                        return price + ''
                    })(),
                }
            case 2:
                return {
                    shop_svalue: (() => {
                        const outNowPrice = ~~(origin_price - shop_svalue)
                        if (outNowPrice < priceWeiter[0] || outNowPrice > priceWeiter[1]) {
                            if (notIsPre === 1) {
                                const maxOutPrice = ~~(origin_price - priceWeiter[1])
                                // console.log('maxOutPrice', maxOutPrice)
                                return maxOutPrice > 100 ? maxOutPrice : 100
                            }
                            return 'del'
                        }
                        // 判断价格最大最小值
                        return ~~shop_svalue
                    })()
                }
            case 3:
                return {
                    shop_svalue: (() => {
                        const outsvaPrice = Math.ceil(origin_price * shop_svalue / 100)
                        const minZekou = ~~((priceWeiter[1] / origin_price * 100))
                        if (outsvaPrice < priceWeiter[0] || outsvaPrice > priceWeiter[1]) {
                            if (notIsPre === 1) {
                                return minZekou <= 10 ? 10 : minZekou
                            }
                            return 'del'
                        }
                        return shop_svalue
                    })()
                }
            default:
                break;
        }
    }
    autoLogsSave(res, formaters) {
        // 自动活动日志保存
        const _this = this
        const { id } = _this.run_item
        const logData = {
            res,
            data: formaters,
            activit_id: id,
            time: moment().format('YYYY-MM-DD HH:mm:ss'),
        }
        const findItemnoer = _this.dly_activity_list.find(item => item.id === id)
        if (findItemnoer) {
            formaters.promotion_goods.forEach(item => {
                const oildsetdata = findItemnoer.addLtaLpConfig.promotion_goods.find(item2 => item2.product_id === item.product_id)
                oildsetdata.useNumber++
            })
        }
        _this.dly_activity_list.forEach(item => {
            if (item.id === id) {
                item.status = 3 // 3:进行次数
                item.autoSetConfig.useNumber = item.autoSetConfig.useNumber + 1
            }
        })
        chrome.storage.local.set({ [_this.storegeText]: _this.dly_activity_list }, function () {
            // console.log('保存成功, 通知到页面')
            notify({
                title: '抖羚羊通知',
                message: `店铺${_this.shopInfo.shop_name}，已经创建活动${formaters.title}，请前往抖店查看`,
                // buttons: [{
                //     title: '打开抖店',
                //     cb: function () {
                //         chrome.tabs.create({ url: 'https://fxg.jinritemai.com/ffa/marketing/coupon/home' }, (id) => {
                //         })
                //     }
                // }],
                requireInteraction: false,
                timeout: 5000
            })
            requerconetntAll('', 'dly_reload_autodata').then(res => {
                // console.log('通知页面刷新数据成功')
            })
        })
        chrome.storage.local.get(_this.autoLogsText, function (result) {
            if (result[_this.autoLogsText]) {
                result[_this.autoLogsText].push(logData)
                const deletOldLogs = result[_this.autoLogsText].filter((itemLog) => {
                    // 如果activit_id 没有包含在_this.dly_activity_list id中则删除
                    const findItem = _this.dly_activity_list.find(item => item.id === itemLog.activit_id)
                    if (findItem) {
                        return true
                    }
                    return false

                })
                chrome.storage.local.set({ [_this.autoLogsText]: deletOldLogs }, function () {
                    requerconetntAll('', 'dly_reload_autodata').then(res => {
                        // console.log('通知页面刷新数据成功')
                    })
                })
                return
            }
            chrome.storage.local.set({ [_this.autoLogsText]: [logData] }, function () {
                requerconetntAll('', 'dly_reload_autodata').then(res => {
                    // console.log('通知页面刷新数据成功')
                })
            })

        })
        setTimeout(() => {
            // 创建完成后等待5秒
            _this.run_status = false
            _this.runSetActivityFunc()
        }, 5000)

    }
    initAutStatus(data) {
        // console.log('初始化自动活动状态', data)
        if (data && data.shop_id) {
            this.shopInfo = { id: data.shop_id }
        }
        this.loginOuterStatus = false
    }
}


const runAct = new InitRunAutoActivity()
runAct.getActivityList()
setInterval(() => {
    runAct.getActivityList()
}, 0.5 * 60000)
export default runAct

